package com.enhe.gck.utils;
import java.util.concurrent.Executor;
import java.util.concurrent.ThreadPoolExecutor;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.AsyncConfigurer;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

@Configuration
@EnableAsync
public class ThreadConfig implements AsyncConfigurer {
    @Value("${Async.ThreadPool.CorePoolSize}")
    private int CorePoolSize;
    @Value("${Async.ThreadPool.MaxPoolSize}")
    private int MaxPoolSize;
    @Value("${Async.ThreadPool.QueueCapacity}")
    private int QueueCapacity;
    @Value("${Async.ThreadPool.KeepAliveSeconds}")
    private int KeepAliveSeconds;
    @Value("${Async.ThreadPool.ThreadNamePrefix}")
    private String ThreadNamePrefix;

    @Bean
    public Executor getAsyncExecutor() {
        ThreadPoolTaskExecutor threadPoolTaskExecutor = new ThreadPoolTaskExecutor();
        // 设置核心线程数
        threadPoolTaskExecutor.setCorePoolSize(CorePoolSize);
        // 设置最大线程数
        threadPoolTaskExecutor.setMaxPoolSize(MaxPoolSize);
        // 设置工作队列大小
        threadPoolTaskExecutor.setQueueCapacity(QueueCapacity);
        //设置空闲线程死亡时间
        threadPoolTaskExecutor.setKeepAliveSeconds(KeepAliveSeconds);
        //前缀
        threadPoolTaskExecutor.setThreadNamePrefix(ThreadNamePrefix);
        // 设置拒绝策略.当工作队列已满,线程数为最大线程数的时候,接收新任务抛出RejectedExecutionException异常
        threadPoolTaskExecutor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        // 初始化线程池
        threadPoolTaskExecutor.initialize();
        return threadPoolTaskExecutor;
    }
}

